<template>
  <div class="statistics-container">
    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stat-card neu-card">
        <div class="stat-icon" style="background: linear-gradient(135deg, #81C784, #4CAF50);">
          <el-icon><Reading /></el-icon>
        </div>
        <div class="stat-info">
          <h3>{{ statistics.totalBooks || 0 }}</h3>
          <p>馆藏图书</p>
        </div>
      </div>
      
      <div class="stat-card neu-card">
        <div class="stat-icon" style="background: linear-gradient(135deg, #64B5F6, #2196F3);">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-info">
          <h3>{{ statistics.borrowedBooks || 0 }}</h3>
          <p>借出图书</p>
        </div>
      </div>
      
      <div class="stat-card neu-card">
        <div class="stat-icon" style="background: linear-gradient(135deg, #FFD54F, #FFC107);">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-info">
          <h3>{{ statistics.totalUsers || 0 }}</h3>
          <p>注册用户</p>
        </div>
      </div>
      
      <div class="stat-card neu-card">
        <div class="stat-icon" style="background: linear-gradient(135deg, #E57373, #F44336);">
          <el-icon><DataAnalysis /></el-icon>
        </div>
        <div class="stat-info">
          <h3>{{ statistics.totalBorrows || 0 }}</h3>
          <p>借阅次数</p>
        </div>
      </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-section">
      <!-- 图书分类分布 -->
      <div class="chart-card neu-card">
        <h3>图书分类分布</h3>
        <div class="chart-container" ref="categoryChartRef"></div>
      </div>
      
      <!-- 月度借阅趋势 -->
      <div class="chart-card neu-card">
        <h3>月度借阅趋势</h3>
        <div class="chart-container" ref="monthlyChartRef"></div>
      </div>
    </div>
    
    <!-- 热门图书 -->
    <div class="popular-books neu-card">
      <h3>热门借阅图书</h3>
      <el-table :data="statistics.topBooks || []" style="width: 100%" class="neu-table-wrapper">
        <el-table-column prop="title" label="书名" min-width="200" />
        <el-table-column prop="borrowCount" label="借阅次数" width="120" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <router-link :to="`/dashboard/books?id=${scope.row.id}`" class="view-link">
              查看详情
            </router-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Reading, Document, User, DataAnalysis } from '@element-plus/icons-vue'
import { statisticsService } from '../api/services'
import * as echarts from 'echarts/core'
import { BarChart, PieChart, LineChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  BarChart,
  PieChart,
  LineChart,
  CanvasRenderer
])

// 统计数据
const statistics = ref({
  totalBooks: 0,
  availableBooks: 0,
  borrowedBooks: 0,
  totalUsers: 0,
  totalBorrows: 0,
  categoryDistribution: [],
  monthlyBorrows: [],
  topBooks: []
})

// 图表引用
const categoryChartRef = ref(null)
const monthlyChartRef = ref(null)
let categoryChart = null
let monthlyChart = null

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await statisticsService.getStatistics()
    if (response.code === 200) {
      statistics.value = response.data
      // 初始化图表
      initCharts()
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 初始化图表
const initCharts = () => {
  // 确保DOM已经渲染
  setTimeout(() => {
    initCategoryChart()
    initMonthlyChart()
  }, 100)
}

// 初始化分类图表
const initCategoryChart = () => {
  if (!categoryChartRef.value) return
  
  // 销毁旧图表
  if (categoryChart) {
    categoryChart.dispose()
  }
  
  // 创建新图表
  categoryChart = echarts.init(categoryChartRef.value)
  
  // 准备数据
  const categoryData = statistics.value.categoryDistribution || []
  
  // 设置图表选项
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: categoryData.map(item => item.name)
    },
    series: [
      {
        name: '图书分类',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: categoryData.map(item => ({
          value: item.value,
          name: item.name
        }))
      }
    ],
    color: [
      '#4CAF50', '#2196F3', '#FFC107', '#F44336', 
      '#9C27B0', '#00BCD4', '#FF9800', '#795548'
    ]
  }
  
  // 设置图表
  categoryChart.setOption(option)
}

// 初始化月度借阅图表
const initMonthlyChart = () => {
  if (!monthlyChartRef.value) return
  
  // 销毁旧图表
  if (monthlyChart) {
    monthlyChart.dispose()
  }
  
  // 创建新图表
  monthlyChart = echarts.init(monthlyChartRef.value)
  
  // 准备数据
  const monthlyData = statistics.value.monthlyBorrows || []
  
  // 设置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: monthlyData.map(item => item.month),
        axisTick: {
          alignWithLabel: true
        }
      }
    ],
    yAxis: [
      {
        type: 'value'
      }
    ],
    series: [
      {
        name: '借阅次数',
        type: 'bar',
        barWidth: '60%',
        data: monthlyData.map(item => item.count),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#2196F3' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
  
  // 设置图表
  monthlyChart.setOption(option)
}

// 处理窗口大小变化
const handleResize = () => {
  if (categoryChart) {
    categoryChart.resize()
  }
  if (monthlyChart) {
    monthlyChart.resize()
  }
}

onMounted(() => {
  fetchStatistics()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (categoryChart) {
    categoryChart.dispose()
  }
  if (monthlyChart) {
    monthlyChart.dispose()
  }
})
</script>

<style scoped>
@import '../assets/styles/neumorphism.css';

.statistics-container {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

/* 统计卡片样式 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: white;
  font-size: 24px;
}

.stat-info h3 {
  font-size: 24px;
  margin: 0 0 5px 0;
  color: var(--text-primary);
}

.stat-info p {
  margin: 0;
  color: var(--text-secondary);
}

/* 图表区域样式 */
.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
}

.chart-card {
  padding: 20px;
}

.chart-card h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: var(--text-primary);
}

.chart-container {
  height: 400px;
  width: 100%;
}

/* 热门图书样式 */
.popular-books {
  padding: 20px;
}

.popular-books h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: var(--text-primary);
}

.view-link {
  color: var(--primary-blue);
  text-decoration: none;
  transition: color 0.3s;
}

.view-link:hover {
  color: var(--primary-blue-dark);
}
</style>